package com.chinazyjr.framework.web.accessControl;


import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestRateListener implements FileAlterationListener{
	
	private static final Logger LOGGER = LoggerFactory.getLogger("LOGGER.WEB_API_REQUEST");
	
	public RequestRateListener() {

	}
	
    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {
    	
    }

	@Override
    public void onFileChange(File file) {
		LOGGER.info("request_rate monitor file changed.");
    	FileInputStream inputStream = null;
    	try {
			inputStream = new FileInputStream(file);
			Properties properties = new Properties();
			properties.load(inputStream);
			Object cfgSwitch = properties.get(RequestRateLimitManager.REQUEST_RATE_SWITCH);
			if ((cfgSwitch==null || !"true".equals(cfgSwitch.toString()))) {
				RequestRateLimitManager.shutdown();
				LOGGER.info("request_rate monitor shutdown.");
			}else {
				RequestRateLimitManager.shutdown();
				RequestRateLimitManager.start(properties);
				LOGGER.info("request_rate monitor restart.");
			}
			inputStream.close();
    	} catch (Exception e) {
			e.printStackTrace();
		}
    }

	@Override
	public void onDirectoryCreate(File directory) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDirectoryChange(File directory) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDirectoryDelete(File directory) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onFileCreate(File file) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onFileDelete(File file) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStop(FileAlterationObserver observer) {
		// TODO Auto-generated method stub
		
	}

}